package org.example.util;




import org.apache.commons.collections.CollectionUtils;
import org.example.dto.base.Result;
import org.example.enums.ResultCodeEnum;


import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * 基于反射注解基础校验工具类
 *
 */
public class ValidationUtil {

	public static final String CONVERT_FAILED = "Failed to convert property value of type";

	private static String successMsg = "校验通过";

	private static Validator validator;

	static {
		ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
		validator = vf.getValidator();
	}

	/**
	 * 基础校验
	 * 
	 * @param t
	 * @return
	 */
	public static <T> Result validate(T t) {
		Set<ConstraintViolation<T>> set = validator.validate(t);
		if (CollectionUtils.isNotEmpty(set)) {
			return new Result(false, ResultCodeEnum.FAIL.getId(),set.iterator().next().getMessage());
		}
		return new Result(true,successMsg);
	}
}
